

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="“ 常在河边走，哪能不湿鞋。” ——若发现文章内容有误，敬请指正，望不吝赐教，谢谢!@[toc]  参考资料 视频资料 以往记录   Web项目实战 | 购物系统v2.0 | 开发记录（一）需求分析 | 技术选型 | 系统设计 | 数据表设计 | SpringBoot、SSM、Thymeleaf、Bootstrap…     Web项目实战 | 购物系统v2.0 | 开发记录（二）搭建Sprin">
<meta property="og:type" content="article">
<meta property="og:title" content="Web项目实战 _ 购物系统v2.0 _ 开发记录（七）SpringBoot整合Shiro框架进行身份认证 _ Shiro 加盐(MD5+Salt)验证登陆 _ 数据表结构优化避免外键+设置中间表">
<meta property="og:url" content="http://example.com/2022/02/12/Web%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98%20_%20%E8%B4%AD%E7%89%A9%E7%B3%BB%E7%BB%9Fv2.0%20_%20%E5%BC%80%E5%8F%91%E8%AE%B0%E5%BD%95%EF%BC%88%E4%B8%83%EF%BC%89SpringBoot%E6%95%B4%E5%90%88Shiro%E6%A1%86%E6%9E%B6%E8%BF%9B%E8%A1%8C%E8%BA%AB%E4%BB%BD%E8%AE%A4%E8%AF%81%20_%20Shiro%20%E5%8A%A0%E7%9B%90(MD5+Salt)%E9%AA%8C%E8%AF%81%E7%99%BB%E9%99%86%20_%20%E6%95%B0%E6%8D%AE%E8%A1%A8%E7%BB%93%E6%9E%84%E4%BC%98%E5%8C%96%E9%81%BF%E5%85%8D%E5%A4%96%E9%94%AE+%E8%AE%BE%E7%BD%AE%E4%B8%AD%E9%97%B4%E8%A1%A8/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="“ 常在河边走，哪能不湿鞋。” ——若发现文章内容有误，敬请指正，望不吝赐教，谢谢!@[toc]  参考资料 视频资料 以往记录   Web项目实战 | 购物系统v2.0 | 开发记录（一）需求分析 | 技术选型 | 系统设计 | 数据表设计 | SpringBoot、SSM、Thymeleaf、Bootstrap…     Web项目实战 | 购物系统v2.0 | 开发记录（二）搭建Sprin">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/d3fdf98502144f939f5d91e98783130f.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/4eacb1dac4a94a73823f535c7441cb87.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/1e7fd572b5ba4061a933850000bb84d6.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/fd7be5fff7e543c98302e0e693fc2b04.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/f6f2f58e08204828b8169fbc714e4985.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/b3c16218c0234adb91eb8a41ca2580fa.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/6891612856104deebf6de1f7c590a17e.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/f63722afd33746c5aa27d833e0908239.png">
<meta property="article:published_time" content="2022-02-12T13:28:38.000Z">
<meta property="article:modified_time" content="2022-08-22T15:50:51.380Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="JavaWeb">
<meta property="article:tag" content="项目实战:购物系统v2.0">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/d3fdf98502144f939f5d91e98783130f.png">
  
  
  
  <title>Web项目实战 _ 购物系统v2.0 _ 开发记录（七）SpringBoot整合Shiro框架进行身份认证 _ Shiro 加盐(MD5+Salt)验证登陆 _ 数据表结构优化避免外键+设置中间表 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Web项目实战 _ 购物系统v2.0 _ 开发记录（七）SpringBoot整合Shiro框架进行身份认证 _ Shiro 加盐(MD5+Salt)验证登陆 _ 数据表结构优化避免外键+设置中间表"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-02-12 21:28" pubdate>
          2022年2月12日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          90 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Web项目实战 _ 购物系统v2.0 _ 开发记录（七）SpringBoot整合Shiro框架进行身份认证 _ Shiro 加盐(MD5+Salt)验证登陆 _ 数据表结构优化避免外键+设置中间表</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <blockquote>
<p>“ 常在河边走，哪能不湿鞋。” ——若发现文章内容有误，敬请指正，望不吝赐教，谢谢!<br>@[toc]</p>
</blockquote>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><hr>
<p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1uz4y197Zm">视频资料</a></p>
<h1 id="以往记录"><a href="#以往记录" class="headerlink" title="以往记录"></a>以往记录</h1><hr>
<blockquote>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/122722369">Web项目实战 | 购物系统v2.0 | 开发记录（一）需求分析 | 技术选型 | 系统设计 | 数据表设计 | SpringBoot、SSM、Thymeleaf、Bootstrap…</a></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/122726356">Web项目实战 | 购物系统v2.0 | 开发记录（二）搭建SpringBoot+SSM框架环境 | 配置Druid+MyBatis | 基于Bootstrap实现登陆页面| 图片验证码接口</a></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/122743352">Web项目实战 | 购物系统v2.0 | 开发记录（三）分页显示 | 根据商品名称进行模糊查询</a></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/122773805">Web项目实战 | 购物系统v2.0 | 开发记录（四）单个页面单个请求解决根据商品类型进行分页查询 | 使用省市区三级联动 | 使用JQuery 插件实现图片上传</a></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/122787974">Web项目实战 | 购物系统v2.0 | 开发记录（五）| 使用base64编码实现头像修改 | 用户个人信息修改 | JQuery动态提示</a></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/122799137">Web项目实战 | 购物系统v2.0 | 开发记录（六）商品详情页面 | 游客访问主页 | 运用Bootstrap4轻量级弹窗实现提示</a></li>
</ul>
</blockquote>
<h1 id="一、运行环境"><a href="#一、运行环境" class="headerlink" title="一、运行环境"></a>一、运行环境</h1><hr>
<ul>
<li>windows10</li>
<li>IDEA 2021.1 专业版</li>
<li>JDK8</li>
<li>SpringBoot2</li>
<li>Druid 1.2.5</li>
<li>Bootstrap 4.6.0</li>
<li>MySQL 8</li>
<li>Navicat 11</li>
</ul>
<h1 id="二、数据表结构优化"><a href="#二、数据表结构优化" class="headerlink" title="二、数据表结构优化"></a>二、数据表结构优化</h1><hr>
<h2 id="2-1-避免外键并添加中间表"><a href="#2-1-避免外键并添加中间表" class="headerlink" title="2.1 避免外键并添加中间表"></a>2.1 避免外键并添加中间表</h2><p>作为一个商城项目，数据表结构一定是非常重要的，笔者之前使用的数据表结构比较繁杂，一张表包含的信息比较多，比如用户表User：除了用户基本信息外，还包含了创建人、创建时间、修改人、修改时间、用户角色这样的字段，导致在修改信息时非常的不便，同时字段信息过多也会影响效率，现在可将其分离，能做中间表的尽量加一张中间表，比如可以添加一张<strong>用户角色表</strong>，表示某个用户对应的角色，作为一张中间表进行查询。</p>
<p><strong>优化前：</strong></p>
<p><img src="https://img-blog.csdnimg.cn/d3fdf98502144f939f5d91e98783130f.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>优化后：</strong><br><img src="https://img-blog.csdnimg.cn/4eacb1dac4a94a73823f535c7441cb87.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>优化后数据表中不存在外键约束，增删改更加方便，只要清楚中间表是哪一个，在进行CRUD的时候同步操作就行了。</p>
<p>对于权限表的设计，这里参考视频资料 <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1uz4y197Zm?p=19">【可点击查看】</a>后做一个简要的概括：</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/41ed5603b839412791dbca6514c972a4.png#pic_center">https://img-blog.csdnimg.cn/41ed5603b839412791dbca6514c972a4.png#pic_center</a> &#x3D;70%x)</p>
<ul>
<li>一个用户可能有多个角色，比如[普通用户]、[管理员]</li>
<li>一个角色可能有多个用户，比如有很多个用户的角色都是[普通用户]</li>
<li>一个角色可能有多个权限，比如[普通用户] 可以浏览商品详情页面、修改个人信息等</li>
<li>一个权限可能有多个用户持有，比如[普通用户]、[管理员] 都可以修改个人信息</li>
<li>其中用户角色表、角色权限表都是中间表，前者是根据用户ID存储对应的角色ID，后者是根据角色ID存储对应的权限ID</li>
</ul>
<h2 id="2-2-Shiro权限管理数据持久化策略"><a href="#2-2-Shiro权限管理数据持久化策略" class="headerlink" title="2.2 Shiro权限管理数据持久化策略"></a>2.2 Shiro权限管理数据持久化策略</h2><p>所谓数据持久化就是将数据保存到数据结构里存储，比如保存在MySQL（后续可使用缓存数据库进行优化）</p>
<p>在使用Shiro实现身份认证时，通过读取用户的信息，判断密码是否匹配，若匹配则登录成功，接下来就是授权的部分，按常理来说权限可以直接在Java类或者是配置文件里配置，但是如果在数据库里设置，会更加的方便，这样管理员就能管理其他用户的权限，而不是简单的增删改查。</p>
<p>登录成功后在Shiro框架里重写一个方法来实现对当前用户的授权，此时就需要根据 [用户角色表] 获取对应的角色ID，然后再获取到当前用户的所有角色信息 (<small>ps: 在pojo类可以在User用户实体类里设置 <code>List&lt;Role&gt; roles</code> 成员变量，来存储当前用户的所有角色信息</small>)</p>
<p>获取到角色后，再获取对应的权限，将这些权限设置到Shiro框架提供的对象里，即完成了数据持久化方式的权限管理。举个例子：</p>
<p><img src="https://img-blog.csdnimg.cn/1e7fd572b5ba4061a933850000bb84d6.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>梳理好过程后，接下来就是具体的代码实现。</p>
<h1 id="三、SpringBoot-集成Shiro身份认证"><a href="#三、SpringBoot-集成Shiro身份认证" class="headerlink" title="三、SpringBoot 集成Shiro身份认证"></a>三、SpringBoot 集成Shiro身份认证</h1><hr>
<h2 id="3-1-导入起步依赖"><a href="#3-1-导入起步依赖" class="headerlink" title="3.1 导入起步依赖"></a>3.1 导入起步依赖</h2><p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- shiro整合spring的依赖 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.shiro<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>shiro-spring<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.6.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br><span class="hljs-comment">&lt;!-- shiro整合Thymeleaf的依赖 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.github.theborakompanioni<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>thymeleaf-extras-shiro<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br></code></pre></td></tr></table></figure>

<h2 id="3-2-编写Shiro-Reaml层"><a href="#3-2-编写Shiro-Reaml层" class="headerlink" title="3.2 编写Shiro-Reaml层"></a>3.2 编写Shiro-Reaml层</h2><p><code>CustomerRealm.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config.shiro;<br><br><span class="hljs-keyword">import</span> com.uni.pojo.Perm;<br><span class="hljs-keyword">import</span> com.uni.pojo.Role;<br><span class="hljs-keyword">import</span> com.uni.pojo.User;<br><span class="hljs-keyword">import</span> com.uni.service.PermService;<br><span class="hljs-keyword">import</span> com.uni.service.RoleService;<br><span class="hljs-keyword">import</span> com.uni.service.UserService;<br><span class="hljs-keyword">import</span> com.uni.utils.ApplicationContextUtils;<br><span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationException;<br><span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationInfo;<br><span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationToken;<br><span class="hljs-keyword">import</span> org.apache.shiro.authc.SimpleAuthenticationInfo;<br><span class="hljs-keyword">import</span> org.apache.shiro.authz.AuthorizationInfo;<br><span class="hljs-keyword">import</span> org.apache.shiro.authz.SimpleAuthorizationInfo;<br><span class="hljs-keyword">import</span> org.apache.shiro.realm.AuthorizingRealm;<br><span class="hljs-keyword">import</span> org.apache.shiro.subject.PrincipalCollection;<br><span class="hljs-keyword">import</span> org.apache.shiro.util.ByteSource;<br><span class="hljs-keyword">import</span> org.apache.shiro.util.CollectionUtils;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;<br><span class="hljs-keyword">import</span> org.springframework.util.ObjectUtils;<br><br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CustomerRealm</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AuthorizingRealm</span> &#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    UserService userService;<br>    <span class="hljs-meta">@Autowired</span><br>    RoleService roleService;<br>    <span class="hljs-meta">@Autowired</span><br>    PermService permService;<br>    <span class="hljs-comment">// 授权</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">protected</span> AuthorizationInfo <span class="hljs-title function_">doGetAuthorizationInfo</span><span class="hljs-params">(PrincipalCollection principalCollection)</span> &#123;<br>        <span class="hljs-type">SimpleAuthorizationInfo</span> <span class="hljs-variable">info</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleAuthorizationInfo</span>();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">principal</span> <span class="hljs-operator">=</span> (String) principalCollection.getPrimaryPrincipal();<br>        <span class="hljs-comment">// 获取当前的用户信息</span><br>        <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> userService.getUserByCode(principal);<br>        <span class="hljs-keyword">if</span>(user != <span class="hljs-literal">null</span>)&#123;<br>            <span class="hljs-comment">// 获取用户的角色</span><br>            List&lt;Role&gt; roles = roleService.queryRoleByUserCode(user);<br>            user.setRole(roles);<br>            <span class="hljs-comment">// 赋予当前用户对应的角色信息（相同角色的权限是一致的）</span><br>            <span class="hljs-keyword">if</span>(roles != <span class="hljs-literal">null</span>) &#123;<br>                roles.forEach(role -&gt; &#123;<br>                    info.addRole(role.getRoleName());<br>                    <span class="hljs-comment">// 添加权限</span><br>                    List&lt;Perm&gt; perms = permService.queryPermByRole(role);<br>                    <span class="hljs-keyword">if</span>(!CollectionUtils.isEmpty(perms))<br>                        perms.forEach(perm -&gt;&#123;<br>                            info.addStringPermission(perm.getUrl());<br>                        &#125;);<br>                &#125;);<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> info;<br>    &#125;<br><br>    <span class="hljs-comment">// 认证</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">protected</span> AuthenticationInfo <span class="hljs-title function_">doGetAuthenticationInfo</span><span class="hljs-params">(AuthenticationToken token)</span><br>            <span class="hljs-keyword">throws</span> AuthenticationException &#123;<br>        <span class="hljs-comment">// 获取身份信息</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">principal</span> <span class="hljs-operator">=</span> (String) token.getPrincipal();<br>        <span class="hljs-comment">// 调用业务层，获取数据库里对应的用户信息</span><br>        <span class="hljs-type">User</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> userService.getUserByCode(principal);<br>        <span class="hljs-keyword">if</span>(!ObjectUtils.isEmpty(user))&#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleAuthenticationInfo</span>(<br>                    user.getCode(),<br>                    user.getPassword(),<br>                    ByteSource.Util.bytes(user.getSalt()),<br>                    <span class="hljs-built_in">this</span>.getName());<br>        &#125;<br>        <span class="hljs-keyword">else</span> <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<h2 id="3-3-配置Shiro（设置MDK5-Salt密码验证方式）"><a href="#3-3-配置Shiro（设置MDK5-Salt密码验证方式）" class="headerlink" title="3.3 配置Shiro（设置MDK5+Salt密码验证方式）"></a>3.3 配置Shiro（设置MDK5+Salt密码验证方式）</h2><p><code>ShiroConfig.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config.shiro;<br><br><span class="hljs-keyword">import</span> at.pollux.thymeleaf.shiro.dialect.ShiroDialect;<br><span class="hljs-keyword">import</span> com.uni.pojo.Perm;<br><span class="hljs-keyword">import</span> com.uni.pojo.Role;<br><span class="hljs-keyword">import</span> com.uni.service.PermService;<br><span class="hljs-keyword">import</span> com.uni.service.RoleService;<br><span class="hljs-keyword">import</span> org.apache.shiro.authc.credential.HashedCredentialsMatcher;<br><span class="hljs-keyword">import</span> org.apache.shiro.codec.Base64;<br><span class="hljs-keyword">import</span> org.apache.shiro.realm.Realm;<br><span class="hljs-keyword">import</span> org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;<br><span class="hljs-keyword">import</span> org.apache.shiro.spring.web.ShiroFilterFactoryBean;<br><span class="hljs-keyword">import</span> org.apache.shiro.util.CollectionUtils;<br><span class="hljs-keyword">import</span> org.apache.shiro.web.mgt.CookieRememberMeManager;<br><span class="hljs-keyword">import</span> org.apache.shiro.web.mgt.DefaultWebSecurityManager;<br><span class="hljs-keyword">import</span> org.apache.shiro.web.servlet.Cookie;<br><span class="hljs-keyword">import</span> org.apache.shiro.web.servlet.SimpleCookie;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><br><span class="hljs-keyword">import</span> java.util.Collection;<br><span class="hljs-keyword">import</span> java.util.LinkedHashMap;<br><span class="hljs-keyword">import</span> java.util.List;<br><span class="hljs-keyword">import</span> java.util.Map;<br><br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ShiroConfig</span> &#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    RoleService roleService;<br>    <span class="hljs-meta">@Autowired</span><br>    PermService permService;<br>    <span class="hljs-comment">// 创建 Realm 对象</span><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> CustomerRealm <span class="hljs-title function_">customerRealm</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">CustomerRealm</span> <span class="hljs-variable">customerRealm</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CustomerRealm</span>();<br>        <span class="hljs-comment">// 修改凭证校验匹配器</span><br>        <span class="hljs-type">HashedCredentialsMatcher</span> <span class="hljs-variable">hcm</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashedCredentialsMatcher</span>();<br>        hcm.setStoredCredentialsHexEncoded(<span class="hljs-literal">true</span>);<br>        <span class="hljs-comment">// 设置加密算法为 MD5</span><br>        hcm.setHashAlgorithmName(<span class="hljs-string">&quot;MD5&quot;</span>);<br>        <span class="hljs-comment">// 设置散列次数</span><br>        hcm.setHashIterations(<span class="hljs-number">1024</span>);<br>        customerRealm.setCredentialsMatcher(hcm);<br>        <span class="hljs-keyword">return</span> customerRealm;<br>    &#125;<br>    <span class="hljs-comment">// 安全管理器</span><br>    <span class="hljs-meta">@Bean(name=&quot;securityManager&quot;)</span><br>    <span class="hljs-keyword">public</span> DefaultWebSecurityManager <span class="hljs-title function_">getDefaultWebSecurityManager</span><span class="hljs-params">(</span><br><span class="hljs-params">            <span class="hljs-meta">@Qualifier(&quot;customerRealm&quot;)</span> Realm realm)</span>&#123;<br>        <span class="hljs-type">DefaultWebSecurityManager</span> <span class="hljs-variable">securityManager</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DefaultWebSecurityManager</span>();<br>        securityManager.setRealm(realm);<br>        <span class="hljs-keyword">return</span> securityManager;<br>    &#125;<br>    <span class="hljs-comment">// 过滤链工厂</span><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> ShiroFilterFactoryBean <span class="hljs-title function_">getShiroFilterFactoryBean</span><span class="hljs-params">(</span><br><span class="hljs-params">            <span class="hljs-meta">@Qualifier(&quot;securityManager&quot;)</span> DefaultWebSecurityManager defaultWebSecurityManager)</span>&#123;<br>        <span class="hljs-type">ShiroFilterFactoryBean</span> <span class="hljs-variable">bean</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ShiroFilterFactoryBean</span>();<br>        <span class="hljs-comment">// 设置安全管理器</span><br>        bean.setSecurityManager(defaultWebSecurityManager);<br><br>        Map&lt;String, String&gt; filterMap = <span class="hljs-keyword">new</span> <span class="hljs-title class_">LinkedHashMap</span>&lt;&gt;();<br><br>        <span class="hljs-comment">// 获取所有权限信息 配置数据库的权限信息</span><br>        List&lt;Perm&gt; perms = permService.queryAllPerm();<br>        perms.forEach(perm -&gt;&#123;<br>            filterMap.put(perm.getUrl(),<br>                    String.format(<span class="hljs-string">&quot;perms[%s]&quot;</span>,perm.getUrl()));<br>        &#125;);<br>        <span class="hljs-comment">// 配置公共权限 (游客的权限)</span><br>        filterMap.put(<span class="hljs-string">&quot;/product.html/*&quot;</span>, <span class="hljs-string">&quot;anon&quot;</span>);<br>        filterMap.put(<span class="hljs-string">&quot;/login/*&quot;</span>, <span class="hljs-string">&quot;anon&quot;</span>);<br>        filterMap.put(<span class="hljs-string">&quot;/register/*&quot;</span>, <span class="hljs-string">&quot;anon&quot;</span>);<br>        filterMap.put(<span class="hljs-string">&quot;/login.html&quot;</span>, <span class="hljs-string">&quot;anon&quot;</span>);<br>        bean.setFilterChainDefinitionMap(filterMap);<br>        <span class="hljs-comment">// 设置登录的请求</span><br>        bean.setLoginUrl(<span class="hljs-string">&quot;/login.html&quot;</span>);<br>        <span class="hljs-comment">// 未授权页面</span><br>        bean.setUnauthorizedUrl(<span class="hljs-string">&quot;/login.html&quot;</span>);<br>        <span class="hljs-keyword">return</span> bean;<br>    &#125;<br><br>    <span class="hljs-comment">// 整合 ShiroDialect: 用来整合 shiro thymeleaf</span><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> ShiroDialect <span class="hljs-title function_">getShiroDialect</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ShiroDialect</span>();<br>    &#125;<br>    <span class="hljs-comment">// Shiro注解开发需要的Bean</span><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> AuthorizationAttributeSourceAdvisor <span class="hljs-title function_">getAuthorizationAttributeSourceAdvisor</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">AuthorizationAttributeSourceAdvisor</span>();<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h2 id="3-4-Shiro-MD5-Salt-Hash注册与登陆业务层实现"><a href="#3-4-Shiro-MD5-Salt-Hash注册与登陆业务层实现" class="headerlink" title="3.4 Shiro MD5 + Salt + Hash注册与登陆业务层实现"></a>3.4 Shiro MD5 + Salt + Hash注册与登陆业务层实现</h2><p>生成<strong>随机盐</strong>（默认指定为随机8位的字符串）的工具类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.utils;<br><span class="hljs-keyword">import</span> java.util.Random;<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SaltUtils</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">getSalt</span><span class="hljs-params">(<span class="hljs-type">int</span> n)</span>&#123;<br>        <span class="hljs-type">char</span>[] chars = <span class="hljs-string">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&amp;*()&quot;</span>.toCharArray();<br>        <span class="hljs-type">StringBuilder</span> <span class="hljs-variable">str</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringBuilder</span>();<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; n; i++) &#123;<br>            <span class="hljs-type">char</span> <span class="hljs-variable">ch</span> <span class="hljs-operator">=</span> chars[<span class="hljs-keyword">new</span> <span class="hljs-title class_">Random</span>().nextInt(chars.length)];<br>            str.append(ch);<br>        &#125;<br>        <span class="hljs-keyword">return</span> str.toString();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>Service层代码：</strong>（其中 <code>getPwd()</code> 方法返回的是从前端发送来的<strong>明文</strong>密码）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">register</span><span class="hljs-params">(User user)</span> &#123;<br>      <span class="hljs-comment">/** 字段处理 **/</span><br>      <span class="hljs-comment">// 设置密文密码</span><br>      <span class="hljs-comment">//     生成随机盐</span><br>      <span class="hljs-type">String</span> <span class="hljs-variable">salt</span> <span class="hljs-operator">=</span> SaltUtils.getSalt(<span class="hljs-number">8</span>);<br>      <span class="hljs-comment">//     将随机盐保存到数据库</span><br>      user.setSalt(salt);<br>      <span class="hljs-comment">//     对明文密码进行 md5 + salt + hash散列（指定1024次，这个次数根据需要自定义，不过需和Realm里的配置同步一致）</span><br>      <span class="hljs-type">Md5Hash</span> <span class="hljs-variable">md5Hash</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Md5Hash</span>(user.getPwd(), salt, <span class="hljs-number">1024</span>);<br>      user.setPassword(md5Hash.toHex());<br>      <span class="hljs-comment">// 存储盐，Shiro登录校验专用</span><br>      user.setSalt(salt);<br>      <span class="hljs-comment">//保存用户</span><br>      <span class="hljs-keyword">return</span> userMapper.insert(user);<br>&#125;<br><span class="hljs-keyword">public</span> User <span class="hljs-title function_">login</span><span class="hljs-params">(User user)</span> &#123;<br>    <span class="hljs-type">UsernamePasswordToken</span> <span class="hljs-variable">token</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">UsernamePasswordToken</span>(user.getCode(), user.getPwd(), <span class="hljs-literal">false</span>);<br>    <span class="hljs-type">Subject</span> <span class="hljs-variable">currentUser</span> <span class="hljs-operator">=</span> SecurityUtils.getSubject();<br>    <span class="hljs-keyword">try</span>&#123;<br>        currentUser.login(token);<br>        <span class="hljs-comment">// 登录成功后获取用户所有信息，并设置[生日]字段的格式化</span><br>        <span class="hljs-type">User</span> <span class="hljs-variable">userInfo</span> <span class="hljs-operator">=</span> getUserByCode(user.getCode());<br>        userInfo.setBirthdayString(UserInfoUtils.decodeBirthday(userInfo.getBirthday()));<br>        <span class="hljs-keyword">return</span> userInfo;<br>    &#125; <span class="hljs-keyword">catch</span>(Exception e)&#123;<br>        token.clear();<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="3-5-测试运行"><a href="#3-5-测试运行" class="headerlink" title="3.5 测试运行"></a>3.5 测试运行</h2><p>未登录状态下直接访问个人信息的URL，控制台提示报错：</p>
<p><img src="https://img-blog.csdnimg.cn/fd7be5fff7e543c98302e0e693fc2b04.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>登录状态下正常访问（因为请求的URL保存在数据库中）</p>
<p><img src="https://img-blog.csdnimg.cn/f6f2f58e08204828b8169fbc714e4985.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>数据库中保存的信息：<br><img src="https://img-blog.csdnimg.cn/b3c16218c0234adb91eb8a41ca2580fa.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>关于Salt+MD5的验证登录，Shiro框架已经封装好了，只需要获取到用户输入的账号和明文密码，就可以与数据库信息匹配</p>
<p><img src="https://img-blog.csdnimg.cn/6891612856104deebf6de1f7c590a17e.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>这里需要注意，在配置Shiro框架的Realm时指定的是根据用户账号从Service层获取用户信息，从而设置<strong>密文密码</strong>，同时还指定MDK5算法、Hash碰撞次数，而在实现登录的业务层，是使用<strong>明文密码</strong>封装一个token对象进行消息传递，这里容易混淆，要点就是：<strong>配置时是密文密码，登录时是明文</strong>，剩下的就交给Shiro框架实现。</p>
<h1 id="四、Bug-amp-DeBug"><a href="#四、Bug-amp-DeBug" class="headerlink" title="四、Bug&amp;DeBug"></a>四、Bug&amp;DeBug</h1><hr>
<h2 id="使用Shiro进行加盐身份认证时候报错-CryptoException"><a href="#使用Shiro进行加盐身份认证时候报错-CryptoException" class="headerlink" title="使用Shiro进行加盐身份认证时候报错 CryptoException"></a>使用Shiro进行加盐身份认证时候报错 CryptoException</h2><p>第一次登录没问题，重启web应用后再次登录就出现了以下两个报错</p>
<p>此时登录的业务层代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Service(&quot;userService&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">UserService</span> &#123;<br>    <span class="hljs-meta">@Autowired</span><br>    UserMapper userMapper;<br>    <span class="hljs-meta">@Autowired</span><br>    RoleMapper roleMapper;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> User <span class="hljs-title function_">login</span><span class="hljs-params">(User user)</span> &#123;<br>        <span class="hljs-type">UsernamePasswordToken</span> <span class="hljs-variable">token</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">UsernamePasswordToken</span>(user.getUserCode(), user.getPwd(), <span class="hljs-literal">true</span>);<br>        <span class="hljs-type">Subject</span> <span class="hljs-variable">currentUser</span> <span class="hljs-operator">=</span> SecurityUtils.getSubject();<br>        <span class="hljs-keyword">try</span>&#123;<br>            currentUser.login(token);<br>            <span class="hljs-keyword">return</span> user;<br>        &#125; <span class="hljs-keyword">catch</span>(Exception e)&#123;<br>            token.clear();<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/f63722afd33746c5aa27d833e0908239.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>报错原因：</p>
<p>在创建 UsernamePasswordToken对象进行身份验证时，第三个参数标记了启动<code>rememberMeManager</code>，则默认会启动记住密码的功能，主要在Shiro框架提供的<code>CookieRememberMeManager.java</code>类里实现，在未进行配置的情况下，第一次启动程序shiro使用随机一个密钥加密了cookie，第二次启动程序shiro又重新生成了另一个密钥，故当用户访问页面时，shiro会用之后的密钥去解密上一次密钥加密的cookie，导致解密失败。</p>
<p>解决：在Shiro配置类里配置CookieRememberMeManager</p>
<p>源代码的构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-title function_">CookieRememberMeManager</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-type">Cookie</span> <span class="hljs-variable">cookie</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleCookie</span>(<span class="hljs-string">&quot;rememberMe&quot;</span>);<br>    cookie.setHttpOnly(<span class="hljs-literal">true</span>);<br>    cookie.setMaxAge(<span class="hljs-number">31536000</span>);<br>    <span class="hljs-built_in">this</span>.cookie = cookie;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>配置后：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br>  <span class="hljs-keyword">public</span> CookieRememberMeManager <span class="hljs-title function_">cookieRememberMeManager</span><span class="hljs-params">()</span> &#123;<br>      <span class="hljs-type">CookieRememberMeManager</span> <span class="hljs-variable">cookieRememberMeManager</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CookieRememberMeManager</span>();<br>      <span class="hljs-type">SimpleCookie</span> <span class="hljs-variable">simpleCookie</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">SimpleCookie</span>(<span class="hljs-string">&quot;rememberMe&quot;</span>);<br>      simpleCookie.setMaxAge(<span class="hljs-number">60</span> * <span class="hljs-number">60</span> * <span class="hljs-number">24</span> * <span class="hljs-number">3</span>);       <span class="hljs-comment">// 默认保存3天登录状态</span><br>      cookieRememberMeManager.setCookie(simpleCookie);<br>      cookieRememberMeManager.setCipherKey(Base64.decode(<span class="hljs-string">&quot;UNI!521!1314&quot;</span>));<br>      <span class="hljs-keyword">return</span> cookieRememberMeManager;<br>  &#125;<br></code></pre></td></tr></table></figure>

<p>留个坑，这个BUG还没完全解决，暂时将<code>记住我</code>的功能设置为 false</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98-%E8%B4%AD%E7%89%A9%E7%B3%BB%E7%BB%9Fv2-0/" class="category-chain-item">项目实战:购物系统v2.0</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/JavaWeb/">#JavaWeb</a>
      
        <a href="/tags/%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98-%E8%B4%AD%E7%89%A9%E7%B3%BB%E7%BB%9Fv2-0/">#项目实战:购物系统v2.0</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Web项目实战 _ 购物系统v2.0 _ 开发记录（七）SpringBoot整合Shiro框架进行身份认证 _ Shiro 加盐(MD5+Salt)验证登陆 _ 数据表结构优化避免外键+设置中间表</div>
      <div>http://example.com/2022/02/12/Web项目实战 _ 购物系统v2.0 _ 开发记录（七）SpringBoot整合Shiro框架进行身份认证 _ Shiro 加盐(MD5+Salt)验证登陆 _ 数据表结构优化避免外键+设置中间表/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年2月12日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/02/13/Hadoop%20_%20MapReduce%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%20_%20Partitioner%E5%88%86%E5%8C%BA%20%E8%87%AA%E5%AE%9A%E4%B9%89%E5%88%86%E5%8C%BA%E7%AD%96%E7%95%A5%E6%A1%88%E4%BE%8B%20_%20WritableComparable%20%E5%85%A8%E6%8E%92%E5%BA%8F%20_%20Combiner%E3%80%81OutputFormat/" title="Hadoop _ MapReduce学习笔记 _ Partitioner分区 自定义分区策略案例 _ WritableComparable 全排序 _ Combiner、OutputFormat">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Hadoop _ MapReduce学习笔记 _ Partitioner分区 自定义分区策略案例 _ WritableComparable 全排序 _ Combiner、OutputFormat</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/02/09/Web%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98%20_%20%E8%B4%AD%E7%89%A9%E7%B3%BB%E7%BB%9Fv2.0%20_%20%E5%BC%80%E5%8F%91%E8%AE%B0%E5%BD%95%EF%BC%88%E4%BA%94%EF%BC%89%E4%BD%BF%E7%94%A8base64%E7%BC%96%E7%A0%81%E5%AE%9E%E7%8E%B0%E5%A4%B4%E5%83%8F%E4%BF%AE%E6%94%B9%20_%20%E7%94%A8%E6%88%B7%E4%B8%AA%E4%BA%BA%E4%BF%A1%E6%81%AF%E4%BF%AE%E6%94%B9%20_%20JQuery%E5%8A%A8%E6%80%81%E6%8F%90%E7%A4%BA/" title="Web项目实战 _ 购物系统v2.0 _ 开发记录（五）使用base64编码实现头像修改 _ 用户个人信息修改 _ JQuery动态提示">
                        <span class="hidden-mobile">Web项目实战 _ 购物系统v2.0 _ 开发记录（五）使用base64编码实现头像修改 _ 用户个人信息修改 _ JQuery动态提示</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
